/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.cqcis.com</a>
 */
package cn.rokhdelar.umbrsapi.core.utils;

import org.springframework.beans.BeanUtils;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class FieldUtil {

	public static Map<String, PropertyDescriptor> dtoProps = new ConcurrentHashMap<String, PropertyDescriptor>();

	public static Map<String, Field[]> dtoFields = new ConcurrentHashMap<String, Field[]>();

	public static Field[] getFields(Class<?> cl) {
		Field[] fields = dtoFields.get(cl.getName());
		if (fields == null) {
			fields = cl.getDeclaredFields();
			dtoFields.put(cl.getName(), fields);
		}
		return fields;
	}

	public static Field getFields(Class<?> cl, String fieldName) {
		Field[] fields = getFields(cl);
		Field f = null;
		if (fields != null) {
			for (Field field : fields) {
				if (field.getName().equals(fieldName)) {
					f = field;
					break;
				}
			}
		}
		return f;
	}

	public static PropertyDescriptor getPropDesc(Class<?> cl, Field field) {
		String key = cl.getName() + "_" + field.getType().getName() + "_" + field.getName();
		PropertyDescriptor prop = dtoProps.get(key);
		if (prop == null) {
			PropertyDescriptor[] properties = BeanUtils.getPropertyDescriptors(cl);
			for (PropertyDescriptor descriptor : properties) {
				if (descriptor.getPropertyType() == field.getType() && descriptor.getName().equals(Introspector.decapitalize(field.getName()))) {
					prop = descriptor;
					dtoProps.put(key, prop);
					break;
				}
			}
		}
		return prop;
	}
}
